package com.dfxs.config;

import com.dfxs.pojo.Configuration;
import com.dfxs.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author zhangdongsheng
 * @version 1.0
 * @describe 解析mapper.xml文件 将文件信息封装到MappedStatement对象中,并全部存储到Configuration对象中
 * @date 2020/9/26 8:27
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析mapper.xml文件 将文件信息封装到MappedStatement对象中,并全部存储到Configuration对象中
     * @param inputStream
     * @return
     */
    public void parseMapper(InputStream inputStream) throws DocumentException {
        //读取mapper.xml文件为字节输入流并转换为Document对象
        Document read = new SAXReader().read(inputStream);
        //获取根节点
        Element rootElement = read.getRootElement();

        //获取namespace属性值
        String namespace = rootElement.attributeValue("namespace");

        //获取select标签属性内容,并封装为MappedStatement对象,添加至Configuration对象中的map集合中,以便上层调用
        List<Element> elementList = rootElement.selectNodes("//select");
        for (Element element : elementList) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            String statementId = namespace + "." + id;
            configuration.getMappedStatementMap().put(statementId,mappedStatement);
        }

    }

}
